﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Quellenverwaltung.SRU
{
    public class CQLBuilder : CQLBuilderIF
    {
        public enum Relation { AND, OR, NOT }
        public Relation relation = Relation.AND;
        public Dictionary<String, String> cqlTerms;

        public CQLBuilder()
        {
            cqlTerms = new Dictionary<string, string>();
        }
   
        public string getQuery()
        {
            string cql = "";

            foreach (string key in cqlTerms.Keys)
            {
                cql = extendToCQL(cql, key, cqlTerms[key]);
            }

            cql = "query=" + Uri.EscapeDataString(cql);
            return cql;
        }

        private string extendToCQL(string cql, string key, string value)
        {
            String cqlWork = cql;
            if (!String.IsNullOrEmpty(value))
            {
                if (!String.IsNullOrEmpty(cqlWork))
                {
                    switch (this.relation)
                    {
                        case Relation.NOT: 
                            cqlWork += " NOT ";
                            break;
                        case Relation.OR: 
                            cqlWork += " OR ";
                            break;
                        default: 
                            cqlWork += " AND ";
                            break;
                    }
                }
                cqlWork += key + "=\"" + value + "\"";
            }
            return cqlWork;
        }
    }
}
